import {messages} from "share/common";
import React from 'react';
import {connect} from 'react-redux'
import config from 'config'
import {Button, message ,Spin} from 'antd'
import Chooser from 'components/chooser'
import expenseService from 'containers/my-account/expense.service'

import FileSaver from "file-saver";
import Importer from "components/template/importer/index";


//数据导入组件
class ExternalExpenseImport extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      expenseTypeIds: [],
      loadingCreateTemplate: false
    };
  }

  onSelectExpenseType = value => this.setState({ expenseTypeIds: value.map(i => i.id) });

  //下载导入模板
  downloadTemplate = () => {
    const { expenseTypeIds } = this.state;
    const { expenseReportOID } = this.props;
    this.setState({ loadingCreateTemplate: true }, () => {
      let params = {
        expenseTypeIds,
        expenseReportOID
      };
      expenseService.invoiceTemplateDown(params).then((res)=>{
        let b = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        FileSaver.saveAs(b, `${messages('common-1.key332')/*费用导入模板*/}.xlsx`);
        this.setState({ loadingCreateTemplate: false });
      }).catch((e)=>{
        console.log(e);
        message.error(messages('common-1.key333')/*下载失败，请重试*/);
        this.setState({ loadingCreateTemplate: false });
      })
    });
  };

  onValidate = () => {
    const { expenseTypeIds } = this.state;
    if(expenseTypeIds && !expenseTypeIds.length)
      message.error(messages('common-1.key334')/*请先选择费用类型*/);
    return expenseTypeIds && expenseTypeIds.length;
  };

  render() {
    const { expenseReportOID, formOID, userOID, applicationOID, btnName } = this.props;
    const { loadingCreateTemplate, expenseTypeIds } = this.state;

    return (
      <Importer
        btnName={btnName}
        btnProps={{type: 'default'}}
        modalOptions={{title: messages('common-1.key335')/*批量导入费用*/}}
        asyncMode={true}
        onValidate={this.onValidate}
        infoMessage={messages('common-1.key336')/*上传模板请确认与【1】中所选费用类型一致*/}
        asyncModeMessage={
          <section>
            <p style={{marginBottom: 16}}>{messages('common-1.key337')/*导入过程预计需要15分钟*/}</p>
            <p>{messages('common-1.key338')/*在此期间您可以进行其他操作，但请不要修改报销单。*/}</p>
            <p>{messages('common-1.key339')/*导入完成后,您会收到一封邮件通知,然后刷新报销单页面查看导入结果*/}</p>
          </section>
        }
        uploadOptions={{
          listenUrl: `${config.budgetUrl}/api/budget/batch/transaction/logs`,
          uploadUrl: '/api/expense/import',
          uploadParams: {
            claimOID: expenseReportOID,
            expenseTypeIds: expenseTypeIds,
            ownerOID: userOID
          }
        }}
        template={
          <div className='left-template external-expense-import' >
            <h3 className='left-template-title'>{messages('common-1.key340')/*创建模板*/}</h3>
            <p style={{marginBottom: 10}}>1. {messages('common-1.key341')/*选择费用类型*/}</p>
            <Chooser
              type='externalExpense'
              labelKey='name'
              valueKey='id'
              onChange={this.onSelectExpenseType}
              maxNum={10}
              listExtraParams={{ formOID ,userOID ,applicationOID }}
            />
            <p style={{marginTop: 20}}>2. {messages('common-1.key342')/*点击下载导入模板*/}</p>
            <Spin spinning={loadingCreateTemplate} tip={messages('common-1.key343')/*正在生成文件...*/}>
              <div className='btn-box'>
                <Button
                  type='link'
                  icon="download"
                  disabled={!expenseTypeIds.length}
                  onClick={this.downloadTemplate}
                >
                  {messages('common-1.key332')/*费用导入模板*/}
                </Button>
              </div>
            </Spin>
          </div>
        }
      />
    );
  }
}

ExternalExpenseImport.propTypes = {
  templateUrl: React.PropTypes.string,    //模版下载接口
  uploadUrlKey: React.PropTypes.string,  //上传接口
  listenUrl: React.PropTypes.string,    //监听上传状态接口，不需要写transactionID变量
  errorUrl: React.PropTypes.string,    //错误信息下载接口，不需要写transactionID变量
  title: React.PropTypes.string,      //标题
  fileName: React.PropTypes.string,  //下载文件名
  onOk: React.PropTypes.func,       //导入成功回调
  afterClose: React.PropTypes.func,//关闭后的回调
  expenseReportOID:React.PropTypes.string, //报销单oid
  formOID: React.PropTypes.string,    //表单oid
  userOID: React.PropTypes.string,  //用户OID
};

ExternalExpenseImport.defaultProps = {
  title: '导入',
  fileName: '导入文件',
  listenUrl: '',
  createTableShow: true,//创建表格示例是否显示
  listentSwitch: true,//上传文件后直接回调
  expenseReportOID:null,
  formOID:null,
  userOID:null,
  onOk: () => {
  },
  afterClose: () => {
  },
};

function mapStateToProps() {
  return {}
}

export default connect(mapStateToProps)(ExternalExpenseImport);
